﻿using System;
using System.Web.UI;

namespace DeployWebLibUtils
{
    public static class Extensions
    {
        /// <summary>
        /// Extension method to detect if specified control is invoking callback action to server
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public static bool IsInvokingCallback(Control control)
        {
            if (control != null)
            {
                return string.Compare(control.UniqueID, control.Page.Request.Params["__CALLBACKID"], true) == 0;
            }

            return false;
        }

        public static Type GetWebEmbeddControlType(Type userControl)
        {
            string assemblyName = userControl.Assembly.GetName().Name;
            string controlNamespace = userControl.Namespace;

            string folderPart = string.Empty;
            if (controlNamespace.StartsWith(assemblyName))
            {
                folderPart = controlNamespace.Replace(assemblyName, "");
            }
            
            if (!string.IsNullOrEmpty(folderPart) && folderPart.StartsWith("."))
            {
                folderPart = folderPart.Remove(0, 1).Replace(".", "_").ToLowerInvariant();
            }

            string extension = "";
            if (userControl.BaseType == typeof(Page))
            {
                extension = "aspx";
            }
            else if (userControl.BaseType == typeof(UserControl))
            {
                extension = "ascx";
            }

            string resultTypeName = string.Format("ASP.{0}{1}_{2}, {3}",
                string.IsNullOrEmpty(folderPart) ? string.Empty : folderPart + "_",
                userControl.Name.ToLowerInvariant(), extension, userControl.Assembly.FullName);

            Type resultType = Type.GetType(resultTypeName, false);

            return resultType;
        }

        public static string GetWebEmbeddControlFullTypeName(Type userControl)
        {
            Type embeddControlType = GetWebEmbeddControlType(userControl);
            return embeddControlType != null ? embeddControlType.AssemblyQualifiedName : string.Empty;
        }
    }
}
